package com.studentmanagement.ui;

import com.studentmanagement.model.Enrollment;
import com.studentmanagement.model.User;
import com.studentmanagement.service.EnrollmentService;
import com.studentmanagement.service.CourseService;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.List;

public class GradeManagementPanel extends JPanel {
    private EnrollmentService enrollmentService;
    private CourseService courseService;
    private JTable gradeTable;
    private DefaultTableModel tableModel;
    private JButton addButton;
    private JButton editButton;
    private JButton deleteButton;
    private JButton refreshButton;
    private JTextField searchField;
    private JButton searchButton;
    private JComboBox<String> filterComboBox;
    
    private Integer courseId; // 特定课程ID
    private User currentUser; // 当前用户

    public GradeManagementPanel() {
        this.enrollmentService = new EnrollmentService();
        this.courseService = new CourseService();
        initComponents();
        setupLayout();
        setupListeners();
        loadGradeData();
    }
    
    /**
     * 创建特定课程的成绩管理面板
     * @param courseId 课程ID
     * @param user 当前用户
     */
    public GradeManagementPanel(Integer courseId, User user) {
        this.enrollmentService = new EnrollmentService();
        this.courseService = new CourseService();
        this.courseId = courseId;
        this.currentUser = user;
        
        initComponents();
        setupLayout();
        setupListeners();
        
        // 加载特定课程的成绩数据
        loadCourseGradeData();
        
        // 修改标题
        JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        JLabel titleLabel = new JLabel("课程成绩管理");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 18));
        titlePanel.add(titleLabel);
        add(titlePanel, BorderLayout.NORTH);
    }

    private void initComponents() {
        // 表格列名
        String[] columnNames = {"ID", "学生姓名", "学号", "课程名称", "课程代码", "成绩", "状态", "选课日期"};
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false; // 表格不可编辑
            }
        };
        gradeTable = new JTable(tableModel);
        gradeTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        gradeTable.getTableHeader().setReorderingAllowed(false);
        
        // 按钮初始化
        addButton = new JButton("添加选课");
        editButton = new JButton("录入成绩");
        deleteButton = new JButton("删除");
        refreshButton = new JButton("刷新");
        searchField = new JTextField(15);
        searchButton = new JButton("搜索");
        
        // 状态过滤器
        String[] filterOptions = {"全部", "已选", "已退选", "已完成"};
        filterComboBox = new JComboBox<>(filterOptions);
    }

    private void setupLayout() {
        setLayout(new BorderLayout(10, 10));
        setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 搜索区域
        JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        searchPanel.add(new JLabel("搜索:"));
        searchPanel.add(searchField);
        searchPanel.add(searchButton);
        searchPanel.add(new JLabel("状态:"));
        searchPanel.add(filterComboBox);

        // 按钮区域
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        buttonPanel.add(addButton);
        buttonPanel.add(editButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(refreshButton);

        // 北边区域组合搜索和按钮
        JPanel northPanel = new JPanel(new BorderLayout());
        northPanel.add(searchPanel, BorderLayout.WEST);
        northPanel.add(buttonPanel, BorderLayout.EAST);

        // 添加组件到主面板
        add(northPanel, BorderLayout.NORTH);
        add(new JScrollPane(gradeTable), BorderLayout.CENTER);
    }

    private void setupListeners() {
        addButton.addActionListener(this::onAdd);
        editButton.addActionListener(this::onEdit);
        deleteButton.addActionListener(this::onDelete);
        refreshButton.addActionListener(e -> {
            if (courseId != null) {
                loadCourseGradeData();
            } else {
                loadGradeData();
            }
        });
        searchButton.addActionListener(e -> searchGrades());
        filterComboBox.addActionListener(e -> filterByStatus());
    }

    // 加载特定课程的成绩数据
    private void loadCourseGradeData() {
        if (courseId == null) {
            return;
        }
        
        tableModel.setRowCount(0); // 清空表格
        List<Enrollment> enrollments = enrollmentService.getEnrollmentsByCourseId(courseId);
        for (Enrollment enrollment : enrollments) {
            Object[] rowData = {
                enrollment.getId(),
                enrollment.getStudentName(),
                enrollment.getStudentNumber(),
                enrollment.getCourseName(),
                enrollment.getCourseCode(),
                formatGrade(enrollment.getGrade()),
                formatStatus(enrollment.getStatus()),
                enrollment.getEnrollmentDate()
            };
            tableModel.addRow(rowData);
        }
    }

    private void loadGradeData() {
        tableModel.setRowCount(0); // 清空表格
        List<Enrollment> enrollments = enrollmentService.getAllEnrollments();
        for (Enrollment enrollment : enrollments) {
            Object[] rowData = {
                enrollment.getId(),
                enrollment.getStudentName(),
                enrollment.getStudentNumber(),
                enrollment.getCourseName(),
                enrollment.getCourseCode(),
                formatGrade(enrollment.getGrade()),
                formatStatus(enrollment.getStatus()),
                enrollment.getEnrollmentDate()
            };
            tableModel.addRow(rowData);
        }
    }
    
    private String formatGrade(String grade) {
        if (grade == null || grade.trim().isEmpty()) {
            return "暂无";
        }
        try {
            double numericGrade = Double.parseDouble(grade);
            return String.format("%.1f", numericGrade);
        } catch (NumberFormatException e) {
            return grade; // 如果不是数字，直接返回原始值
        }
    }
    
    private String formatStatus(String status) {
        if ("ACTIVE".equals(status)) {
            return "已选";
        } else if ("DROPPED".equals(status)) {
            return "已退选";
        } else if ("COMPLETED".equals(status)) {
            return "已完成";
        } else {
            return status;
        }
    }
    
    private String getStatusCode(String displayStatus) {
        switch (displayStatus) {
            case "已选": return "ACTIVE";
            case "已退选": return "DROPPED";
            case "已完成": return "COMPLETED";
            default: return null;
        }
    }

    private void searchGrades() {
        String keyword = searchField.getText().trim();
        if (keyword.isEmpty()) {
            if (courseId != null) {
                loadCourseGradeData();
            } else {
                loadGradeData();
            }
            return;
        }
        
        tableModel.setRowCount(0);
        List<Enrollment> enrollments;
        
        if (courseId != null) {
            // 如果是特定课程，则在该课程内搜索学生
            enrollments = enrollmentService.getEnrollmentsByCourseId(courseId);
            // 过滤结果（因为没有特定课程的搜索方法，所以在客户端进行过滤）
            enrollments.removeIf(e -> 
                !e.getStudentName().contains(keyword) && 
                !e.getStudentNumber().contains(keyword));
        } else {
            enrollments = enrollmentService.searchEnrollments(keyword);
        }
        
        for (Enrollment enrollment : enrollments) {
            Object[] rowData = {
                enrollment.getId(),
                enrollment.getStudentName(),
                enrollment.getStudentNumber(),
                enrollment.getCourseName(),
                enrollment.getCourseCode(),
                formatGrade(enrollment.getGrade()),
                formatStatus(enrollment.getStatus()),
                enrollment.getEnrollmentDate()
            };
            tableModel.addRow(rowData);
        }
    }
    
    private void filterByStatus() {
        String selectedFilter = (String) filterComboBox.getSelectedItem();
        if ("全部".equals(selectedFilter)) {
            if (courseId != null) {
                loadCourseGradeData();
            } else {
                loadGradeData();
            }
            return;
        }
        
        String statusCode = getStatusCode(selectedFilter);
        if (statusCode == null) {
            return;
        }
        
        tableModel.setRowCount(0);
        List<Enrollment> enrollments;
        
        if (courseId != null) {
            // 如果是特定课程，则在该课程内过滤状态
            enrollments = enrollmentService.getEnrollmentsByCourseId(courseId);
            // 过滤结果
            enrollments.removeIf(e -> !statusCode.equals(e.getStatus()));
        } else {
            enrollments = enrollmentService.getEnrollmentsByStatus(statusCode);
        }
        
        for (Enrollment enrollment : enrollments) {
            Object[] rowData = {
                enrollment.getId(),
                enrollment.getStudentName(),
                enrollment.getStudentNumber(),
                enrollment.getCourseName(),
                enrollment.getCourseCode(),
                formatGrade(enrollment.getGrade()),
                formatStatus(enrollment.getStatus()),
                enrollment.getEnrollmentDate()
            };
            tableModel.addRow(rowData);
        }
    }

    private void onAdd(ActionEvent e) {
        EnrollmentDialog dialog;
        if (courseId != null) {
            // 如果是特定课程，则预设课程ID
            dialog = new EnrollmentDialog(null, courseId);
        } else {
            dialog = new EnrollmentDialog(null);
        }
        dialog.setVisible(true);
        if (dialog.isSaved()) {
            if (courseId != null) {
                loadCourseGradeData();
            } else {
                loadGradeData();
            }
        }
    }

    private void onEdit(ActionEvent e) {
        int selectedRow = gradeTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请先选择一条记录！", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        
        Integer enrollmentId = (Integer) tableModel.getValueAt(selectedRow, 0);
        Enrollment enrollment = enrollmentService.getEnrollmentById(enrollmentId);
        if (enrollment != null) {
            GradeEditDialog dialog = new GradeEditDialog(enrollment);
            dialog.setVisible(true);
            if (dialog.isSaved()) {
                if (courseId != null) {
                    loadCourseGradeData();
                } else {
                    loadGradeData();
                }
            }
        }
    }

    private void onDelete(ActionEvent e) {
        int selectedRow = gradeTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请先选择一条记录！", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        
        int confirm = JOptionPane.showConfirmDialog(this, "确认删除所选选课记录吗？", "确认删除", JOptionPane.YES_NO_OPTION);
        if (confirm == JOptionPane.YES_OPTION) {
            Integer enrollmentId = (Integer) tableModel.getValueAt(selectedRow, 0);
            boolean success = enrollmentService.deleteEnrollment(enrollmentId);
            if (success) {
                if (courseId != null) {
                    loadCourseGradeData();
                } else {
                    loadGradeData();
                }
                JOptionPane.showMessageDialog(this, "删除成功！", "提示", JOptionPane.INFORMATION_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(this, "删除失败！", "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
} 